﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;

namespace PingTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Scan();
        }

        private int i = 30;
        private void Scan()
        {
            Console.WriteLine("[192.168.3."+i.ToString()+"] try scaning..."+DateTime.Now);
            Scan("192.168.3." + (i++).ToString(), bo => {
                if (bo)
                {
                    var str = "192.168.3." + i.ToString() + "  " + DateTime.Now;
                    addText(str);
                    Console.WriteLine("=========================================[Success]===:192.168.3." + (i - 1).ToString() + "   " + DateTime.Now);
                }
                if (i > 255) return;
                Scan();
            });
        }

        private void Scan(string ip,Action<bool> action)
        {
            Ping ping = new Ping();
            ping.PingCompleted += (s, e) => {
                if (e.Reply.Status == IPStatus.Success)
                    action?.Invoke(true);
                else
                    action?.Invoke(false);
            };
            ping.SendAsync(IPAddress.Parse(ip),2000,null);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }

        private void addText(string text)
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new MethodInvoker(() =>
                {
                    richTextBox1.AppendText(text);
                    richTextBox1.AppendText("\n");
                }));
            }
            else
            {
                richTextBox1.AppendText(text);
                richTextBox1.AppendText("\n");
            }
        }
    }
}
